from pynput import keyboard

import threading
import time


class KeyboardCls(threading.Thread):

    def __init__(self):
        print("keyboard 初始化")
        super().__init__()

        self.keyboard_listen = keyboard.Listener()
        self.__keyboard_running_flag = True
        self.mouse_running_flag = 4  # 1 开始， 2 暂停, 3 结束, 4 other

    def keyboard_check(self):
        if not self.__keyboard_running_flag:
            return False

    # 按下键盘时回调的函数
    def on_press(self, key):
        print('{0} 按下'.format(key))
        if key == keyboard.Key.esc:
            self.__keyboard_running_flag = False
            self.mouse_running_flag = 3
            return False
        if str(key) == "<49>":  # ctrl+1
            self.mouse_running_flag = 1
        elif str(key) == "<50>":  # ctrl+2
            self.mouse_running_flag = 2
        elif str(key) == "<51>":  # ctrl+3
            self.mouse_running_flag = 3
        return self.keyboard_check()

    # 释放键盘时回调的函数
    def on_release(self, key):
        print('{0} 释放'.format(key))
        return self.keyboard_check()

    def run(self) -> None:
        self.keyboard_start()

    def keyboard_start(self):
        print("键盘监听开始。。。。。。")
        self.keyboard_listen = keyboard.Listener(on_press=self.on_press, on_release=self.on_release)
        self.keyboard_listen.start()
        self.keyboard_listen.join()

    def keyboard_stop(self):
        self.__keyboard_running_flag = False
        keyboard.Controller().press(keyboard.Key.esc)


if __name__ == '__main__':
    kb = KeyboardCls()
    kb.start()
    time.sleep(5)
    kb.keyboard_stop()
